namespace ETestIT.DataAccess
{
    using System;
    using System.Collections.Generic;
    using Domain.Entities;
    using Domain.Repositories;
    using Repository;

    public class UserRepositoryImpl : IUserRepository
    {
        public IList<User> GetAll()
        {
            const string sql = @"SELECT Id, Name, Password FROM Users";

            return new FluentCommand<User>(sql)
                .SetMap(UserMap)
                .AsList();
        }

        public User GetByNameAndPassword(string name, string password)
        {
            const string sql = @"SELECT Id, Name, Password FROM Users WHERE Name = @Name and Password = @Password";

            return new FluentCommand<User>(sql)
                .AddString("Name", name)
                .AddString("Password", password)
                .SetMap(UserMap)
                .AsSingle();
        }

        public void Add(User resume)
        {
            resume.Id = Guid.NewGuid();
            new FluentCommand<string>("INSERT INTO Users (Id, Name ,Password) VALUES (@Id, @Name ,@Password)")
                .AddGuid("Id", resume.Id)
                .AddString("Name", resume.Name)
                .AddString("Password", resume.Password)
                .AsNonQuery();
        }

        public void Update(User user)
        {
            new FluentCommand<string>(@"UPDATE Users
                                           SET 
                                              Name = @Name,
                                              Password = @Password
                                         WHERE Id = @Id")
                .AddGuid("Id", user.Id)
                .AddString("Name", user.Name)
                .AddString("Password", user.Password)
                .AsNonQuery();
        }

        public void Delete(Guid id)
        {
            new FluentCommand<string>("DELETE FROM Users WHERE Id = @Id")
                .AddGuid("Id", id)
                .AsNonQuery();
        }

        private User UserMap(DataReader reader)
        {
            return new User
            {
                Id = reader.GetGuid("Id"),
                Name = reader.GetString("Name"),
                Password = reader.GetString("Password")
            };
        }

        public User GetById(Guid id)
        {
            const string sql = @"SELECT Id, Name, Password FROM Users WHERE Id = @Id";

            return new FluentCommand<User>(sql)
                .AddGuid("Id", id)
                .SetMap(UserMap)
                .AsSingle();
        }
    }
}